package com.clouddot.baipai.ui.fragment.H_MainFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.TargetUrl;
import com.clouddot.baipai.model.beam.getCourseById.courseInfoByid;
import com.clouddot.baipai.model.beam.getCourseById.getCourseByIdResponse;
import com.clouddot.baipai.model.beam.getCourseList.courseInfo;
import com.clouddot.baipai.model.beam.getCourseList.getCourseListResponse;
import com.clouddot.baipai.ui.activity.H_SMainActivity;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.adapter.H_Adapter.courseInfoRecyclerAdapter;
import com.clouddot.baipai.ui.adapter.H_Adapter.homeWorkRecyclerAdapter;
import com.clouddot.baipai.ui.dialog.H_Dialog.H_ContentDailog;
import com.clouddot.baipai.ui.util.recycleView.DivierItemLinear;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class H_HomeworkFragment extends BaseFragment {

    private View view;
    private Context context;

    private ConstraintLayout constraintLayout2;
    private ScrollView constraintLayout1;
    private TextView name ;
    private RecyclerView recyclerView ,recyclerView2;
    private LinearLayout last,next;
    private RelativeLayout relativeLayout;
//    private RelativeLayout scanCard;

    private homeWorkRecyclerAdapter homeWorkRecyclerAdapter;
    private courseInfoRecyclerAdapter courseInfoRecyclerAdapter;

    private List<courseInfo> list = new ArrayList<courseInfo>();
    private List<courseInfoByid> courseInfoist = new ArrayList<courseInfoByid>();

    private int CurrentPage = 1;
    private int pageCount = 0;
    private Boolean isRunning = false;
    private String currentBtn = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();

        view = LayoutInflater.from(context).inflate(R.layout.h_f_homeworkfg,null);
    }

    @Override
    protected void initControls() {
        super.initControls();
        recyclerView = view.findViewById(R.id.recycle2);
        recyclerView2 = view.findViewById(R.id.recycle);

        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        homeWorkRecyclerAdapter = new homeWorkRecyclerAdapter(context,list);
        recyclerView.setAdapter(homeWorkRecyclerAdapter);

        recyclerView2.setLayoutManager(new LinearLayoutManager(context));
        recyclerView2.addItemDecoration(new DivierItemLinear(context,DivierItemLinear.VERTICAL_LIST));
        recyclerView2.setItemAnimator(new DefaultItemAnimator());
        courseInfoRecyclerAdapter = new courseInfoRecyclerAdapter(context,courseInfoist);
        recyclerView2.setAdapter(courseInfoRecyclerAdapter);

        name = view.findViewById(R.id.name);
        constraintLayout1 = view.findViewById(R.id.left);
        constraintLayout2 = view.findViewById(R.id.right);

        constraintLayout1.startAnimation(animation1);
        constraintLayout2.startAnimation(animation2);

        last = view.findViewById(R.id.last);
        next = view.findViewById(R.id.next);
        relativeLayout = view.findViewById(R.id.loading);
        ImageView loading = view.findViewById(R.id.imgloading);
        loading.startAnimation(loadingAnim);

//        scanCard = view.findViewById(R.id.scanCard);
    }

    @Override
    protected void setListener() {
        super.setListener();
        last.setOnClickListener(lastListener);
        next.setOnClickListener(nextListener);
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (dailog != null) dailog.closeDialog();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(Env.getAppContext().isInitial) {
                constraintLayout1.setVisibility(View.VISIBLE);
                constraintLayout2.setVisibility(View.VISIBLE);
                relativeLayout.setVisibility(View.VISIBLE);
                recyclerView2.setVisibility(View.GONE);
                runThreadAction("getCourseList");
        }
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
         super.runThreadActionExceute(actionName);
        if(actionName.equals("getCourseList")){
            if(Env.getAppContext().StudentId != null) {
                return Env.getAppPresenter().getCourseList(TargetUrl.studentId + Env.getAppContext().StudentId);
            }else{
                return Env.getAppPresenter().getCourseList(TargetUrl.classId + Env.getAppContext().classId);
            }
        }else
        {
            return Env.getAppPresenter().getCourseById(actionName,CurrentPage,Env.getAppContext().itemCount);
        }
    }

    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);

        if(actionName.equals("getCourseList")){
            final getCourseListResponse response = (getCourseListResponse) result;
            if(response.isSuccess()){
                list = response.list;
                list.get(0).flag = true;
                currentBtn = list.get(0).getId();
                homeWorkRecyclerAdapter = new homeWorkRecyclerAdapter(context,list);
                homeWorkRecyclerAdapter.setbtnOnclicker(new homeWorkRecyclerAdapter.btnOnclicker() {
                    @Override
                    public void onClicked(int position) {
                        H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

                        name.setText(list.get(position).getCourseName());
                        if(isRunning) {
                            isRunning = false;
                            for (courseInfo courseInfo : list) {
                                courseInfo.flag = false;
                            }
                            list.get(position).flag = true;
                            homeWorkRecyclerAdapter.notifyDataSetChanged();
                            pageCount = 0;
                            CurrentPage = 1;
                            relativeLayout.setVisibility(View.VISIBLE);
                            recyclerView2.setVisibility(View.GONE);
                            currentBtn =list.get(position).getId();
                            runThreadAction(currentBtn);
                        }
                    }
                });
                recyclerView.setAdapter(homeWorkRecyclerAdapter);
                name.setText(list.get(0).getCourseName());
                runThreadAction(currentBtn);
            }else{
                isRunning = true;
                relativeLayout.setVisibility(View.GONE);
                ToastUtil.showToast(context, response.getErrMsg());
                return;
            }
        }else{
            relativeLayout.setVisibility(View.GONE);
            final getCourseByIdResponse response  = (getCourseByIdResponse) result;
            if(response.isSuccess()){
                if(!response.list.isEmpty()) {
                    courseInfoist = response.list;
                    pageCount = Integer.parseInt(response.PageCount);
                }else{
                    courseInfoist =new ArrayList<>();
                    courseInfoByid demo = new courseInfoByid();
                    demo.setDetail("");
                    demo.setTitle("当前课程无作业");
                    demo.setCreateTime("");
                    courseInfoist.add(demo);
                }
                courseInfoRecyclerAdapter = new courseInfoRecyclerAdapter(context, courseInfoist);
                courseInfoRecyclerAdapter.setbtnOnclicker(new courseInfoRecyclerAdapter.btnOnclicker() {
                    @Override
                    public void onClicked(int position) {
                        H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;
                        if (!courseInfoist.get(position).getTitle().equals("当前课程无作业")) {
                            if (dailog != null) dailog.closeDialog();
                            dailog = new H_ContentDailog(context);
                            TextViews = dailog.getTextViews();
                            TextViews.get(0).setText(courseInfoist.get(position).getTitle());
                            TextViews.get(1).setText("发布时间：" + courseInfoist.get(position).getCreateTime());
                            TextViews.get(2).setText("正在加载...");
                            final String html = EscapeUnescapeUtil.unescape(courseInfoist.get(position).getDetail());
                            ThreadPool.getInstance().execute(new Runnable() {
                                @Override
                                public void run() {
                                    sp = Html.fromHtml(html, new Html.ImageGetter() {
                                        @Override
                                        public Drawable getDrawable(String source) {
                                            String s =  source.contains("http") ? source:Env.getAppContext().IP + source;

                                            InputStream is = null;
                                            try {
                                                is = (InputStream) new URL(s).getContent();
                                                Drawable d = Drawable.createFromStream(is, null);
                                                d.setBounds(0, 0, d.getIntrinsicWidth(),
                                                        d.getIntrinsicHeight());
                                                is.close();
                                                return d;
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                return null;
                                            }
                                        }
                                    }, null);
                                    mhandler.sendEmptyMessage(2);
                                }
                            });

                            close = dailog.getCloseView();
                            close.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

                                    dailog.closeDialog();
                                }
                            });
                            dailog.showDialog();
                        }
                    }
                });
                recyclerView2.setAdapter(courseInfoRecyclerAdapter);
            }else {
                isRunning = true;
                ToastUtil.showToast(context, response.getErrMsg());
                return;
            }
            isRunning = true;
            relativeLayout.setVisibility(View.GONE);
            recyclerView2.setVisibility(View.VISIBLE);
        }

    }

    private H_ContentDailog dailog;
    private ImageView close;
    private List<TextView> TextViews;
    private Spanned sp;


    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case  2:
                    TextViews.get(2).setText(sp);
                    break;
            }
        }
    };


    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    private View.OnClickListener lastListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;


            if (CurrentPage <= 1){
                ToastUtil.showToast(context,"当前是第一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView2.setVisibility(View.GONE);
            CurrentPage--;
            runThreadAction(currentBtn);
        }
    };

    private View.OnClickListener nextListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;


            if (CurrentPage >= pageCount){
                ToastUtil.showToast(context,"当前是最后一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView2.setVisibility(View.GONE);
            CurrentPage++;
            runThreadAction(currentBtn);
        }
    };

}
